#include "stdafx.h"
#include "tapplication.h"
#include <QtNetwork>


TApplication::TApplication(int argc, char **argv)
    :QApplication(argc,argv)
    ,m_isRunning(false)
    ,m_setting(NULL)
{  
     setOrganizationName("beixnuengx");
     setApplicationName("BeixnuengxPlayer");  
  
    QString serverName = applicationName();
    QLocalSocket socket;
    socket.connectToServer(serverName);
    if (socket.waitForConnected(500))
    {
        m_isRunning = true;
        return;
    }
    m_localServer = new QLocalServer(this);
    connect(m_localServer, SIGNAL(newConnection()), this, SLOT(NewLocalConnection()));
    if (!m_localServer->listen(serverName)) 
    {
        if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
            && QFile::exists(m_localServer->serverName()))
        {
                QFile::remove(m_localServer->serverName());
                m_localServer->listen(serverName);
        }
    }
    m_setting = new QSettings(QSettings::UserScope, organizationName(), applicationName());
}

TApplication::~TApplication()
{
    if(m_setting)
        delete m_setting;
}

void TApplication::NewLocalConnection()  
{  
    QLocalSocket *socket = m_localServer->nextPendingConnection();  
    if (!socket)
        return;
    emit activateMainWindow();
    delete socket;
}

bool TApplication::IsRunning()
{
    return m_isRunning;
}

QSettings* TApplication::Settings()
{
    return m_setting;
}